package com.xiang.xoa;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.daimajia.numberprogressbar.NumberProgressBar;

import java.util.HashMap;
import java.util.Map;

public class WebFragment extends Fragment
    implements ObservableWebView.OnScrollChangedListener {

    private static final String TAG = WebFragment.class.getSimpleName();

    private static final String EXTRA_URL = "extra_url";
    private static final String EXTRA_TITLE = "extra_title";

    private static final Map<String, Integer> URL_POSITION_CACHES = new HashMap<>();

    protected NumberProgressBar progressbar;
    protected ObservableWebView webView;

    String url, title;
    int positionHolder;
    boolean overrideTitleEnabled = true;

    /**
     * Using newIntent trick, return WebActivity Intent, to avoid `public static`
     * constant
     * variable everywhere
     *
     * @return Intent to start WebActivity
     */
    public static Bundle newBundle(String extraTitle, String extraURL) {
        Bundle bundle = new Bundle();
        bundle.putString(EXTRA_TITLE, extraTitle);
        bundle.putString(EXTRA_URL, extraURL);
        return bundle;
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View root = inflater.inflate(R.layout.web_fragment, container, false);
        /* setContentView(R.layout.web_activity_web); */

        progressbar = (NumberProgressBar) root.findViewById(R.id.progressbar);
        webView = (ObservableWebView) root.findViewById(R.id.web_view);

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setAppCacheEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setSupportZoom(true);
        settings.setDomStorageEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        webView.setWebChromeClient(new ChromeClient());
        webView.setWebViewClient(new ReloadableClient());
        webView.setOnScrollChangedListener(this);
        // webView.addJavascriptInterface(new JSInterface(), "JSInterface");

        webView.loadUrl(getUrl());

        return root;
    }

    public String getUrl(){
        return url==null?getArguments().getString(EXTRA_URL):url;
    }

    public String getTitle(){
        return title==null?"":title;
    }

    public void setOverrideTitleEnabled(boolean enabled) {
        this.overrideTitleEnabled = enabled;
    }


//    public void setTitle(CharSequence title) {
//        super.setTitle(title);
//        textSwitcher.setText(title);
//    }


    private void refresh() {
        webView.reload();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (webView.canGoBack()) {
                        webView.goBack();
                    }
            }
        }
        return true;
    }


//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.web_menu_web, menu);
//        return true;
//    }


//    @Override public boolean onOptionsItemSelected(MenuItem item) {
//        int id = item.getItemId();
//        if (id == R.id.action_refresh) {
//            refresh();
//            return true;
//        } else if (id == R.id.action_copy_url) {
//            ClipBoards.copyToClipBoard(this, webView.getUrl());
//            Toast.makeText(this, R.string.web_tip_copy_done, Toast.LENGTH_SHORT).show();
//            return true;
//        } else if (id == R.id.action_open_url) {
//            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//            if (intent.resolveActivity(getPackageManager()) != null) {
//                startActivity(intent);
//            } else {
//                Toast.makeText(this, R.string.web_tip_open_fail, Toast.LENGTH_LONG).show();
//            }
//            return true;
//        }
//        return super.onOptionsItemSelected(item);
//    }

//
//    @SuppressWarnings("deprecation")
//    @Override protected void onDestroy() {
//        final String url = webView.getUrl();
//        int bottom = (int) Math.floor(webView.getContentHeight() * webView.getScale() * 0.8f);
//        if (positionHolder >= bottom) {
//            URL_POSITION_CACHES.remove(url);
//        } else {
//            URL_POSITION_CACHES.put(url, positionHolder);
//        }
//        super.onDestroy();
//        if (webView != null) webView.destroy();
//    }


//    @Override public void finish() {
//        super.finish();
//        overridePendingTransition(0, 0);
//    }


    @Override public void onScrollChanged(WebView v, int x, int y, int oldX, int oldY) {
        positionHolder = y;
    }


    private class ChromeClient extends WebChromeClient {

        @Override public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            progressbar.setProgress(newProgress);
            if (newProgress == 100) {
                progressbar.setVisibility(View.INVISIBLE);
            } else {
                progressbar.setVisibility(View.VISIBLE);
            }
        }


        @Override public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (overrideTitleEnabled) {
//                setTitle(title);
            }
        }
    }


    private class ReloadableClient extends WebViewClient {

        @SuppressWarnings("deprecation")
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null) view.loadUrl(url);
            return true;
        }


        @Override public void onPageCommitVisible(WebView view, String url) {
            super.onPageCommitVisible(view, url);
            Integer _position = URL_POSITION_CACHES.get(url);
            int position = _position == null ? 0 : _position;
            view.scrollTo(0, position);
        }


        @Override public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            boolean isBlackPage = false;
            for (String blackKey : SwipeBlacklist.get()) {
                if (url.contains(blackKey)) {
                    isBlackPage = true;
                    break;
                }
            }
            if (isBlackPage) {
                Toast.makeText(view.getContext(),
                    R.string.web_tip_swipe_back_disabled, Toast.LENGTH_LONG)
                    .show();
            } else {
            }
        }
    }
}
